//
//  LJM_RANK_ViewController.m
//  wind
//
//  Created by 李金明 on 16/1/19.
//  Copyright © 2016年 李金明. All rights reserved.
//

#import "LJM_RANK_ViewController.h"
#import "LJM_RANK_MAIN_Model.h"
#import "LJM_RANK_REFS_MODEL.h"
#import "LJM_RANK_MAIN_TableViewCell.h"
#import "LJM_RANK_WebView_ViewController.h"
#import "LJM_SONG_Root_Sub_ViewController.h"
#import "SYPMusicPlay_ViewController.h"
#import <STKAudioPlayer.h>
#define CELLHEIGHT 120
@interface LJM_RANK_ViewController () <UITableViewDataSource, UITableViewDelegate, RANK_WebView_BackDelegate, SubBackNavigationDelegate>
#pragma SONG_Root_SubVC的协议方法
- (void)SubBackNavigationDelegate;
#pragma webView的协议方法 返回
- (void)backRANK_WebView_Delegate;
@property (nonatomic, retain) UIButton *bactButton;
@property (nonatomic, retain) UIView *barview;
@property (nonatomic, retain) UITableView *tableV;
@property (nonatomic, retain) NSMutableArray *mainArr;


@property (nonatomic, retain) SYPMusicPlay_ViewController *musicPlayer;

@end

@implementation LJM_RANK_ViewController
- (void)dealloc
{
    self.backDelegate = nil;
    [_musicPlayer release];
    [_mainArr release];
    [_URLSTR release];
    [_tableV release];
    [_bactButton release];
    [_barview release];
    [super dealloc];
}
- (void)setURLSTR:(NSString *)URLSTR
{
    if (_URLSTR != URLSTR) {
        [_URLSTR release];
        _URLSTR = [URLSTR retain];
    }
    //获取数据
    [self getDataStr:URLSTR];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //自定义navigationBar
    [self navigationBarView];
    //添加tableview
    [self addTableView];
    self.musicPlayer = [SYPMusicPlay_ViewController shareMusicPlayVC];
    
}
#pragma 添加tableView
- (void)addTableView
{
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 100) style:UITableViewStylePlain];
    self.tableV.backgroundColor = [UIColor clearColor];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    self.tableV.showsHorizontalScrollIndicator = NO;
    self.tableV.showsVerticalScrollIndicator = NO;
//    self.tableV.rowHeight = self.view.frame.size.height - BUTTONVIEWHEIGHT - 55;

    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
}
#pragma tableView的协议方法
#pragma 数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (0 != self.mainArr.count) {
        if (0 == section) {
            LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:0];

            
            return model.refsArr.count;
        } else if (1 == section) {
            LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:1];
            
            return model.refsArr.count;
        }
        else {
            LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:2];
            
            return model.refsArr.count;
        }
 
    } else {
        return 0;
    }
}
#pragma cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *str = @"cell";
    LJM_RANK_MAIN_TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (nil == cell) {
        cell = [[[LJM_RANK_MAIN_TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str] autorelease];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (0 != self.mainArr.count) {

    LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:indexPath.section];
       LJM_RANK_REFS_MODEL *refsModel = [model.refsArr objectAtIndex:indexPath.row];
        [cell.imageV sd_setImageWithURL:[NSURL URLWithString:refsModel.pic] placeholderImage:[UIImage imageNamed:@"zhanwei"]];
        cell.titleLab.text = refsModel.title;
        cell.firstLab.text = [NSString stringWithFormat:@"%ld. %@", (long)1, [[refsModel.songsArr objectAtIndex:0] objectForKey:@"name"]];
        cell.secondLab.text = [NSString stringWithFormat:@"%ld. %@", (long)2, [[refsModel.songsArr objectAtIndex:1] objectForKey:@"name"]];
        cell.threeLab.text = [NSString stringWithFormat:@"%ld. %@", (long)3, [[refsModel.songsArr objectAtIndex:2] objectForKey:@"name"]];
    }
    return cell;
}
#pragma 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return CELLHEIGHT;
}
#pragma 组的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 3;
}
#pragma 组头的内容
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    LJM_RANK_MAIN_Model *model = nil;
    if (0 != self.mainArr.count) {
           model = [self.mainArr objectAtIndex:section];
    }

    return model.name;
}



#pragma 点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

//    if (self.musicPlayer.player) {
//        NSLog(@"存在播放器");
//        [self.musicPlayer.player pause];
//        
//    }
    
   LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:indexPath.section];
    LJM_RANK_REFS_MODEL *refsModel = [model.refsArr objectAtIndex:indexPath.row];
    
    if (0 != refsModel.link.length) {
        LJM_RANK_WebView_ViewController *webView = [[LJM_RANK_WebView_ViewController alloc] init];
        webView.backDelegate = self;
            webView.navigationItem.hidesBackButton = YES;
        webView.url = refsModel.link;
        [self.barview removeFromSuperview];
        [self.navigationController pushViewController:webView animated:YES];
        [webView release];
        
        
        
        
        
    } else {
        LJM_SONG_Root_Sub_ViewController *ROOTVC = [[LJM_SONG_Root_Sub_ViewController alloc] init];
        ROOTVC.backDelegate = self;
        LJM_RANK_MAIN_Model *model = [self.mainArr objectAtIndex:indexPath.section];
        LJM_RANK_REFS_MODEL *refsModel = [model.refsArr objectAtIndex:indexPath.row];
        ROOTVC.type = @"RANK";
        ROOTVC.imageUrl = refsModel.pic;
        ROOTVC._id = refsModel.ranklist_id;
        [self.navigationController pushViewController:ROOTVC animated:YES];
        [ROOTVC release];
        [self.barview removeFromSuperview];
        ROOTVC.navigationItem.hidesBackButton = YES;
    
    }


}




#pragma 获取数据
- (void)getDataStr:(NSString *)str
{
    self.mainArr = [NSMutableArray array];

[LJMNetworkTool getNetWithURL:str body:nil headFile:nil responseStyle:LJMResponseJSON success:^(NSURLSessionDataTask *task, id responseObject) {
    if (responseObject) {
   
    for (NSMutableDictionary *tempDic in responseObject) {
        LJM_RANK_MAIN_Model *model = [[LJM_RANK_MAIN_Model alloc] init];
        [model initWithDic:tempDic];
        model.refsArr = [NSMutableArray array];
        for (NSMutableDictionary *refDic in [tempDic objectForKey:@"refs"]) {
            LJM_RANK_REFS_MODEL *refsmodel = [[LJM_RANK_REFS_MODEL alloc] init];
            [refsmodel initWithDic:refDic];
            refsmodel.pic = [[refDic objectForKey:@"image"] objectForKey:@"pic"];
            refsmodel.songsArr = [NSMutableArray arrayWithArray:[refDic objectForKey:@"songs"]];
            [model.refsArr addObject:refsmodel];
            [refsmodel release];
        }

        [self.mainArr addObject:model];
        [model release];
    }

#pragma 缓存数据到本地
        NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[str hash]];
        // 存储的沙盒路径
        NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        // 归档
        [NSKeyedArchiver archiveRootObject:responseObject toFile:[path_doc stringByAppendingPathComponent:path]];
        
        [self.tableV reloadData];
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    // 缓存的文件夹
    NSString *path = [NSString stringWithFormat:@"%ld.plist", (long)[str hash]];
    NSString *path_doc = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 反归档
    id result = [NSKeyedUnarchiver unarchiveObjectWithFile:[path_doc stringByAppendingPathComponent:path]];
    
    if (result) {
        for (NSMutableDictionary *tempDic in result) {
            LJM_RANK_MAIN_Model *model = [[LJM_RANK_MAIN_Model alloc] init];
            [model initWithDic:tempDic];
            model.refsArr = [NSMutableArray array];
            for (NSMutableDictionary *refDic in [tempDic objectForKey:@"refs"]) {
                LJM_RANK_REFS_MODEL *refsmodel = [[LJM_RANK_REFS_MODEL alloc] init];
                [refsmodel initWithDic:refDic];
                refsmodel.pic = [[refDic objectForKey:@"image"] objectForKey:@"pic"];
                refsmodel.songsArr = [NSMutableArray arrayWithArray:[refDic objectForKey:@"songs"]];
                [model.refsArr addObject:refsmodel];
                [refsmodel release];
            }
            
            [self.mainArr addObject:model];
            [model release];
            [self.tableV reloadData];
        }
    }
}];
    
}
#pragma 自定义navigationBar
- (void)navigationBarView
{
    
    self.barview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, NAVIGATIONBARHEIGHT)];
    self.barview.userInteractionEnabled = YES;
    self.barview.backgroundColor = [UIColor colorWithRed:69 / 255.0 green:175 / 255.0 blue:248 / 255.0 alpha:1.0];
    [self.navigationController.navigationBar addSubview:self.barview];
    [_barview release];
    self.bactButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.bactButton setTitle:@"返回" forState:UIControlStateNormal];
    [self.bactButton addTarget:self action:@selector(backButton) forControlEvents:UIControlEventTouchUpInside];
    [self.bactButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.barview addSubview:self.bactButton];
    [self.bactButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.barview.mas_left).offset(10);
        make.width.mas_equalTo(@50);
        make.bottom.equalTo(self.barview.mas_bottom).offset(-5);
        make.height.mas_equalTo(@30);
    }];
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"排行榜";
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.font = [UIFont boldSystemFontOfSize:20];
    titleLab.textColor = [UIColor whiteColor];
    [self.barview addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.barview.mas_centerX);
        make.width.mas_equalTo(@100);
        make.centerY.equalTo(self.bactButton.mas_centerY);
        make.height.mas_equalTo(@30);
    }];
    
}
#pragma 返回的动作
- (void)backButton
{
    [self.navigationController popViewControllerAnimated:YES];
    [self.barview removeFromSuperview];
    [self.backDelegate backRANKAction];
}
#pragma webView的协议方法 返回
- (void)backRANK_WebView_Delegate
{
    [self navigationBarView];
}
#pragma SONG_Root_SubVC的协议方法
- (void)SubBackNavigationDelegate
{
    [self navigationBarView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
